package org.sxp.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.sxp.common.annotation.SysLog;
import org.sxp.common.utils.AeyeIdUtils;
import org.sxp.common.web.WrapperResponse;
import org.sxp.modules.sys.controller.AbstractController;
import org.sxp.modules.sys.entity.SysUserEntity;
import org.sxp.modules.sys.service.SysUserService;
import org.sxp.modules.sys.shiro.ShiroUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;

/**
 * @author shenxingping
 * @date 2021/12/30
 */
@RestController
@RequestMapping(value = "/")
@Api(description="public", tags = "")
@SysLog(modules = "public", value = "")
public class PublicController extends AbstractController {

    @Autowired
    private SysUserService userService;
    public static final String _LOCAL_HOST = "127.0.0.1";

    @GetMapping("/api/resetPwd")
    public WrapperResponse test(HttpServletRequest request) {
        String host = request.getRemoteHost();
        String serverName = request.getServerName();
        if(StringUtils.isNotBlank(host) && host.equals(serverName) && _LOCAL_HOST.equals(host)){
            SysUserEntity userEntity = userService.getOne(new LambdaQueryWrapper<SysUserEntity>()
                    .eq(SysUserEntity::getUsername, "admin")
            );
            if(userEntity != null){
                String uuid = AeyeIdUtils.generateShortUuid();
                userEntity.setPassword(ShiroUtils.sha256(uuid, userEntity.getSalt()));
                boolean boo = userService.updateById(userEntity);
                if(boo){
                    log.error("管理员密码重置：" + uuid);
                    return WrapperResponse.success("修改成功！密码可查看服务器打印日志");
                }
            }else{
                return WrapperResponse.fail("管理员账号不存在", null);
            }
        }
        return WrapperResponse.fail("非法授权访问", null);
    }

}
